import {
  getSongDetail,
  getSongLyric
} from "../../../services/player"
import {
  parseLyric
} from "../../../utils/parse-lyric"
import playerStore from "../../../store/playerStore"

const app = getApp()
const modeNames=["order","repeat","random"]
// 创建播放器的上下文
const audioContext = wx.createInnerAudioContext()
// pages/music-player/music-player.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageTitles: ['歌曲', '歌词'],
    id: '',
    currentSong: {},
    lyricInfos: [], //歌词的数组
    currentLyricIndex: -1,
    currentLyricText: '',
    currentPage: 0,
    contentHeight: 0,

    playSongList: [], //当前的播放列表
    playSongIndex: 0,

    currentTime: 0,
    durationTime: 0,
    sliderValue: 0,
    iswaiting: false,
    isPlaying: true,
    lyricScrollTop: 0,
    isFristPlay:true,
    playModeIndex: 0 ,//0顺序播放 1，单曲循环2，随机
    playModeName:'order'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取高度
    this.setData({
      contentHeight: app.globalData.contentHeight
    })
    // 播放歌曲
    this.seupPlaySong(options.id)
    // ------从store中获取共享数据
    playerStore.onStates(['playSongList', 'playSongIndex'], ({
      playSongList,
      playSongIndex
    }) => {
      if (playSongList) {
        // console.log(playSongList);
        this.setData({
          playSongList
        })
      }


      if (playSongIndex !== undefined) {
        this.setData({
          playSongIndex
        })
      }

    })
  },
  // -----------------事件监听-------------------
  onleftClickTap(){
console.log("onleftClickTap");
wx.navigateBack()
  },
  // 滑动切换 歌曲歌词
  onSwiperchange(event) {
    // console.log(event.detail.current);
    this.setData({
      currentPage: event.detail.current
    })
  },
  // tabs点击 歌曲歌词
  onTabsItemTap(event) {
    //  console.log(event.currentTarget.dataset.index);
    const index = event.currentTarget.dataset.index
    this.setData({
      currentPage: index
    })
  },
  // onSliderChange点击 
  onSliderChange(event) {
    console.log("onSliderChange");
    this.data.iswaiting = true
    setTimeout(() => {
      this.data.iswaiting = false
    }, 2500)
    // 1,获取点击滑块的位置对应的值
    const value = event.detail.value
    // 2,计算出当前时间
    const currentTime = value / 100 * this.data.durationTime
    // 3,设置给播放器，计算的的当前时间
    audioContext.seek(currentTime / 1000)
    this.setData({
      currentTime
    })
  },
  // 播放或者暂停
  onPlayorPusetap() {
    // if (this.data.isPlaying) {
    if (!audioContext.paused) {
      audioContext.pause()
      this.setData({
        isPlaying: false
      })
    } else {
      audioContext.play()
      this.setData({
        isPlaying: true
      })
    }
  },
  onPrevBtnTap() {
    this.changeNewSong(false)
  },
  onNextBtnTap() {
    this.changeNewSong()
  },
  changeNewSong(isNext = true) {
    // console.log("onNextBtnTap");
    // 1获取之前的数据
    const length = this.data.playSongList.length
    let index = this.data.playSongIndex
    // 2.根据之前的数据计算出新的索引
switch (this.data.playModeIndex) {
  case 0:
    index = isNext ? index + 1 : index - 1
    if (index === length) index = 0
    if (index === -1) index = length - 1
    break;
  case 1:
    
    break;
  case 2:
    index=Math.floor(Math.random()*length)
    break;


}
    // 3,根据索引获取当前歌曲的信息
    // debugger
    const newSong = this.data.playSongList[index]
    console.log(newSong.id);
    // 不保留当前歌曲的数据 -重置数据为空
    this.setData({currentSong:{}})

    this.seupPlaySong(newSong.id)
    // 4,保存最新的索引
    playerStore.setState('playSongIndex', index)
  },
  onModeTap(){
   let modeIndex =this.data.playModeIndex

   modeIndex++
  
   if( modeIndex === 3) modeIndex = 0
   this.setData({playModeIndex:modeIndex,playModeName:modeNames[modeIndex]})
  },
  // ---------播放歌曲-------
  seupPlaySong(id) {
    this.setData({
      id
    })
    // 2,根据id获取数据
    getSongDetail(this.data.id).then(res => {
      // console.log(res.songs[0]);
      this.setData({
        currentSong: res.songs[0],
        durationTime: res.songs[0].dt
      })
    })
    // 3,歌词信息
    getSongLyric(this.data.id).then(res => {
      // console.log(res.lrc.lyric);
      const lrcSting = res.lrc.lyric
      const lyricInfos = parseLyric(lrcSting)
      // console.log(lyricInfos);

      this.setData({
        lyricInfos
      })
    })
    // 4,播放歌曲
    audioContext.stop()
    audioContext.src = `https://music.163.com/song/media/outer/url?id=${this.data.id}.mp3`
    audioContext.autoplay = true
    // 5 监听播放的进度  针对的是播放器实例对象的只监听一次即可 做一个判断
    if(this.data.isFristPlay){
      this.data.isFristPlay=false
      audioContext.onTimeUpdate(() => {
        // console.log('ontiemUpdate---');
        if (!this.data.iswaiting) {
          // 1,记录当前的时间
          this.setData({
            currentTime: audioContext.currentTime * 1000
          })
          // 2，修改滑块的值
          this.setData({
            sliderValue: this.data.currentTime / this.data.durationTime * 100
          })
        }
        //  匹配歌词
        if (!this.data.lyricInfos.length) return
        let index = this.data.lyricInfos.length - 1 //默认是最后一句
        // 匹配到第一个大于的  前面的一个就是
        for (let i = 0; i < this.data.lyricInfos.length; i++) {
          const lyricItem = this.data.lyricInfos[i]
          if (lyricItem.time >= this.data.currentTime) {
            index = i - 1
            break
          }
        }
        if (index === this.data.currentLyricIndex) return
        // console.log(index, this.data.lyricInfos[index].text);
        this.setData({
          currentLyricIndex: index,
          currentLyricText: this.data.lyricInfos[index].text,
          lyricScrollTop: 35 * index
        })
  
  
      })
      // 手动的监听 等待 先暂停  可以播放 手动播放
      audioContext.onWaiting(() => {
        audioContext.pause()
      })
      audioContext.onCanplay(() => {
        audioContext.play()
      })
      // 自动播放下一首
      audioContext.onEnded(()=>{
        this.changeNewSong()
      })
    }
  
  }
})